package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.common.JsonResult;
import org.example.common.util.JwtUtils;
import org.example.common.util.WechatUtils;
import org.example.common.config.BaseErrorException;
import org.example.dto.login.GetTokenReqDTO;
import org.example.dto.wechat.GetOpenIdInfoParamsDTO;
import org.example.dto.wechat.GetOpenIdInfosResultDTO;
import org.example.entity.UserInfoEntity;
import org.example.enums.BaseErrorEnums;
import org.example.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Slf4j
@Api(tags = "登录")
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private WechatUtils wechatUtils;

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation("获取openid")
    @GetMapping("/getOpenid/{code}")
    public JsonResult<String> getOpenid(@PathVariable String code){
        log.info("获取openId:{}",code);
        GetOpenIdInfoParamsDTO build = GetOpenIdInfoParamsDTO.builder()
                .code(code)
                .build();
        GetOpenIdInfosResultDTO openIdInfo = wechatUtils.getOpenIdInfo(build);
        return JsonResult.ok(openIdInfo.getOpenid());
    }


    @ApiOperation("获取token")
    @PostMapping("/getToken")
    public JsonResult getToken(@RequestBody GetTokenReqDTO getTokenReqDTO){
        log.info("获取token：{}",getTokenReqDTO);
        String openId = getTokenReqDTO.getOpenId();
        return Optional.of(Optional.ofNullable(this.userInfoService.lambdaQuery()
                        .eq(UserInfoEntity::getOpenId, openId)
                        .one())
                .orElseGet(() -> {
                    UserInfoEntity userInfoEntity = new UserInfoEntity();
                    userInfoEntity.setOpenId(openId);
                    this.userInfoService.save(userInfoEntity);
                    return userInfoEntity;
                }))
                .map( JwtUtils::createToken)
                .map(JsonResult::ok)
                .orElseThrow(() -> new BaseErrorException(BaseErrorEnums.SYS_ERROR))
        ;
    }
}
